import sqlalchemy

from app.business.user_collection import UserCollectionFindBiz, UserCollectionCreateBiz
from app.datatype import milvus_index
from app.datatype.milvus_content import MilvusContentCreateMdl
from app.datatype.milvus_index import (
    MilvusIndexDetailMdl, MilvusIndexCreateMdl, MilvusIndex, MilvusIndexListFindMdl, MilvusIndexListMdl,
    MilvusIndexDeleteMdl, MilvusIndexUpdateMdl,
)
from app.datatype.user_collection import UserCollection
from app.initializer import g
from app.utils import db_async, milvus_client
from app.utils.db_async import format_all
from app.utils.milvus_do import MilvusDo


class MilvusIndexDetailBiz(MilvusIndexDetailMdl):

    async def detail(self):
        # TODO: 业务逻辑
        pass

#新增milvus索引
class MilvusIndexCreateBiz(MilvusIndexCreateMdl):
    async def create(self):
        milvus_do = MilvusDo()
        result= milvus_do.create_index(collection_name=self.milvus_index)
        if result == "成功":
             print(f"索引 {self.milvus_index} 创建成功")
        else:
            return None
            # print("")
        async with g.db_async_session() as session:

            milvus_index_id =  await db_async.create(
                session=session,
                model=MilvusIndex,
                data={
                    "milvus_index": self.milvus_index,
                    "name": self.name,
                    "file_num": self.file_num,
                    "description": self.description,
                    "create_id": self.create_id,
                    "type":self.type,
                    "user_id": self.user_id
                }
            )
            userCollectionBiz = UserCollectionCreateBiz()

            userCollectionBiz.user_id = self.create_id
            userCollectionBiz.milvus_index_id = milvus_index_id
            await userCollectionBiz.create()
            return milvus_index_id

# 查询知识库列表
class MilvusIndexListBiz(MilvusIndexListFindMdl):
    async def lst(self,current_user):

        # if current_user.role == 1:
        #     # 普通用户
        #     # 查询 sessionList 通过userid order by created_at desc 并且非删除状态
        #     sql_base = (
        #         f"SELECT id,milvus_index,name,(SELECT  COUNT(*) from milvus_content mc where milvus_index_id  = mi.id and is_deleted = 0 ) as file_num,description,type FROM {MilvusIndex.__tablename__} mi"
        #         f" WHERE is_deleted = 0 AND ((user_id = {current_user.id} AND type = 1) OR type = 3) ")
        #     params = {}
        if current_user.role == 2 or current_user.role == 1:
            # 管理员
            # 查询 sessionList 通过userid order by created_at desc 并且非删除状态
            sql_base = (
                f"SELECT id,milvus_index,name,(SELECT  COUNT(*) from milvus_content mc where milvus_index_id  = mi.id and is_deleted = 0 ) as file_num,description ,type FROM {MilvusIndex.__tablename__} mi"
                f" WHERE is_deleted = 0  and user_id = {current_user.id} and type = 1  ")

            milvus_index_biz =UserCollectionFindBiz()
            milvus_index_biz.user_id = current_user.id
            milvus_index_id_list =await  milvus_index_biz.select_now_all()
            if milvus_index_id_list is not  None and  len(milvus_index_id_list) != 0:
                #获取 milvus_index_id_list 为int 类型 并且拼接到sql_base中 id in []
                milvus_index_id_list = [int(item["milvus_index_id"]) for item in milvus_index_id_list]
                sql_base += f" or id in ({','.join(map(str, milvus_index_id_list))})"
            params = {}

        if current_user.role == 3:
            # 超级管理员
            # 查询 sessionList 通过userid order by created_at desc 并且非删除状态
            sql_base = (
                f"SELECT id,milvus_index,name,(SELECT  COUNT(*) from milvus_content mc where milvus_index_id  = mi.id and is_deleted = 0 ) as file_num,description,type FROM {MilvusIndex.__tablename__} mi"
                f" WHERE is_deleted = 0")
            params = {}




        if self.find_name:
            sql_base += " AND name LIKE :find_name"
            params["find_name"] = f"%{self.find_name}%"

        sql_base += " ORDER BY created_at DESC"
        sql = sqlalchemy.text(sql_base)
        async with g.db_async_session() as session:
            result = await session.execute(sql,params)
            rows =  result.fetchall()
            return await format_all(rows, MilvusIndexListMdl.response_fields())


            # rows = result.fetchall()
            # field_names = list(MilvusIndexListMdl.__fields__.keys())
            # # 如果没有数据，返回空列表
            # print("!!!!!!!rows:", rows)
            # if rows is None or not rows or len(rows) == 0:
            #     return []
            #
            # return [MilvusIndexListMdl(**dict(zip(field_names, row))).dict() for row in rows]
    async def lstPer(self,current_user):

        if current_user.role == 2 or current_user.role == 1:
            # 管理员
            # 查询 sessionList 通过userid order by created_at desc 并且非删除状态
            sql_base = (
                f"SELECT id,milvus_index,name,(SELECT  COUNT(*) from milvus_content mc where milvus_index_id  = mi.id and is_deleted = 0 ) as file_num,description ,type FROM {MilvusIndex.__tablename__} mi"
                f" WHERE is_deleted = 0 AND ((user_id = {current_user.id} AND type = 1) OR type = 3) ")

            milvus_index_biz =UserCollectionFindBiz()
            milvus_index_biz.user_id = current_user.id
            milvus_index_id_list =await  milvus_index_biz.select_now_all()
            if milvus_index_id_list is not  None and  len(milvus_index_id_list) != 0:
                #获取 milvus_index_id_list 为int 类型 并且拼接到sql_base中 id in []
                milvus_index_id_list = [int(item["milvus_index_id"]) for item in milvus_index_id_list]
                sql_base += f" or id in ({','.join(map(str, milvus_index_id_list))})"
            params = {}

        if current_user.role == 3:
            # 超级管理员
            # 查询 sessionList 通过userid order by created_at desc 并且非删除状态
            sql_base = (
                f"SELECT id,milvus_index,name,(SELECT  COUNT(*) from milvus_content mc where milvus_index_id  = mi.id and is_deleted = 0 ) as file_num,description ,type FROM {MilvusIndex.__tablename__} mi"
                f" WHERE is_deleted = 0")
            params = {}

        if self.find_name:
            sql_base += " AND name LIKE :find_name"
            params["find_name"] = f"%{self.find_name}%"

        sql_base += " ORDER BY created_at DESC"
        sql = sqlalchemy.text(sql_base)
        async with g.db_async_session() as session:
            result = await session.execute(sql,params)
            rows =  result.fetchall()
            return await format_all(rows, MilvusIndexListMdl.response_fields())


# 删除milvus索引
class MilvusIndexDeleteBiz(MilvusIndexDeleteMdl):
    async def delete(self):
        milvus_do = MilvusDo()
        result = milvus_do.delete_index(collection_name=self.milvus_index)
        if result == "成功":
            print(f"索引 {self.milvus_index} 删除成功")
        else:
            return None

        async with g.db_async_session() as session:

            await db_async.update(
                session=session,
                model=UserCollection,
                data={
                    "is_deleted": 1,
                },
                filter_by={"milvus_index_id": self.id},
            )
            return await db_async.update(
                session=session,
                model=MilvusIndex,
                data={
                    "is_deleted": 1
                },
                filter_by={"id": self.id}
            )

#修改milvus 信息
class MilvusIndexUpdateBiz(MilvusIndexUpdateMdl):
    async def update(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=MilvusIndex,
                data={
                    "name": self.name,
                    "description": self.description,
                },
                filter_by={"id": self.id}
            )

